package com.byxy.student.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.byxy.student.entity.Student;
import com.byxy.student.service.StudentService;

/** 查询学号是否已存在 */
@WebServlet("/servlet/std/getId")
public class GetStudentServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private StudentService studentService;

	// Servlet不支持Spring 的自动注入，需要手动
	@Override
	public void init() throws ServletException {

		super.init();
		if (null == studentService) {
			ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
			studentService = (StudentService) ctx.getBean(StudentService.class);
		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		String id = req.getParameter("id");// 获取表单id
		Student person = studentService.getById(id);
		resp.setContentType("application/json;charset=utf-8");// 指定返回的格式为JSON格式
		resp.setCharacterEncoding("UTF-8");// setContentType与setCharacterEncoding的顺序不能调换，否则还是无法解决中文乱码的问题

		PrintWriter out = null;
		out = resp.getWriter();
		if (person != null) {// 存在
			String jsonStr = "{\"state\":\"-1\"}";
			out.write(jsonStr);
		} else {// 不存在
			String jsonStr = "{\"state\":\"1\"}";
			out.write(jsonStr);
		}
		out.close();
	}

}
